#include <libdswutility/dswavctrl.h>
#include <front_end/decoder/nextchip/nvp1914c.h>

#define DEV_AVCTRL "/dev/nvp1914c.0"

CDswavctrl::CDswavctrl(LPST_ENV_T pEnv)
: CDswbase(pEnv)
, m_nFd(-1)
{
	LOG4CPLUS_DEBUG(log_dsw, "Create CDswavctrl class!");
	m_nFd = open(DEV_AVCTRL, O_RDWR);
	if (m_nFd < 0){
		LOG4CPLUS_ERROR(log_dsw, "Open av device [ " << DEV_AVCTRL << " ] failed!");
		m_nFd = -1;
		return;
	}
	ST_VIDEO_PARAM nVideoParam;
	SendMessage(PMSG_GET_VIDEO_PARAM, &nVideoParam);
	for (int i = 0; i < MAX_CHANNEL_LOCAL; i++){
		ST_IMAGE_ADJ_PARAM nImageAdjParam;
		nImageAdjParam.nCh = nVideoParam.nVParam[i].ch_num;
		nImageAdjParam.pImageParam = &nVideoParam.nVParam[i].imageparam;
		VideoAdj(&nImageAdjParam);
	}
}

CDswavctrl::~CDswavctrl()
{
	if (m_nFd != -1)
		close(m_nFd);
	LOG4CPLUS_DEBUG(log_dsw, "Destroy CDswavctrl class!");
}

void CDswavctrl::VideoAdj(LPST_IMAGE_ADJ_PARAM pImageParam)
{
	if (m_nFd == -1)
		return;
	struct nvp1914c_ioc_data nData;
	int nRet;
	nData.ch = pImageParam->nCh;

	nData.data = (int)((double)pImageParam->pImageParam->brightness / 100 * 255 - 128);
	nRet = ioctl(m_nFd, NVP1914C_SET_BRIGHTNESS, &nData);
	if (nRet != 0)
		LOG4CPLUS_ERROR(log_dsw, "CH [" << pImageParam->nCh << "] NVP1914C_SET_BRIGHTNESS error!");
	nData.data = (int)((double)pImageParam->pImageParam->saturation / 100 * 255);
	nRet = ioctl(m_nFd, NVP1914C_SET_SATURATION, &nData);
	if (nRet != 0)
		LOG4CPLUS_ERROR(log_dsw, "CH [" << pImageParam->nCh << "] NVP1914C_SET_SATURATION error!");
	nData.data = (int)((double)pImageParam->pImageParam->contrast / 100 * 255);
	nRet = ioctl(m_nFd, NVP1914C_SET_CONTRAST, &nData);
	if (nRet != 0)
		LOG4CPLUS_ERROR(log_dsw, "CH [" << pImageParam->nCh << "] NVP1914C_SET_CONTRAST error!");
	nData.data = (int)((double)pImageParam->pImageParam->hue / 100 * 255);
	nRet = ioctl(m_nFd, NVP1914C_SET_HUE, &nData);
	if (nRet != 0)
		LOG4CPLUS_ERROR(log_dsw, "CH [" << pImageParam->nCh << "] NVP1914C_SET_HUE error!");
	
}

void CDswavctrl::AudioAdj(LPST_AUDIO_PARAM pAudioParam)
{
	if (m_nFd == -1)
		return;
	int nAudioVal = (int)((double)pAudioParam->nSpkVol / 100 * 15);
	int nRet = ioctl(m_nFd, NVP1914C_SET_VOL, &nAudioVal);
	if (nRet != 0)
		LOG4CPLUS_ERROR(log_dsw, "NVP1914C_SET_VOL error!");
}

int CDswavctrl::OnMessage(EN_MSG_TYPE nMsgType, void * pParam)
{
	switch(nMsgType){
	case PMSG_SET_VIDEO_ADJ_AUTO:
		{
			LPST_CH_VPARAM pChVParam = (LPST_CH_VPARAM)pParam;
			ST_IMAGE_ADJ_PARAM nImageAdjParam;
			nImageAdjParam.nCh = pChVParam->ch_num;
			nImageAdjParam.pImageParam = &pChVParam->imageparam;
			VideoAdj(&nImageAdjParam);
		}
		break;
	case PMSG_SET_AUDIO_PARAM:
		AudioAdj((LPST_AUDIO_PARAM)pParam);
		break;
	}
	return 0;
}

